package structure;

import java.util.ArrayList;
import java.util.List;

public class ListNode {
    public int val;
    public ListNode next;

    public ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    @Override
    public String toString() {
        ListNode head = this;
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        final List<String> objects = list.stream().map(Object::toString).toList();
        return String.join(", ", objects);
    }

    public static ListNode create(int[] nums) {
        ListNode list = new ListNode();
        ListNode listPtr = list;
        for (int num : nums) {
            final ListNode node = new ListNode();
            node.val = num;
            listPtr.next = node;
            listPtr = node;
        }
        return list.next;
    }

    public static void printList(ListNode head) {
        System.out.println(head.toString());
    }
}
